import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../domain/providers/backup_provider.dart';
import '../../../domain/providers/album_provider.dart';
import '../../../core/di/service_locator.dart';
import '../../widgets/album/album_list.dart';

/// 备份设置页面
class BackupSettingsScreen extends StatefulWidget {
  const BackupSettingsScreen({Key? key}) : super(key: key);

  @override
  State<BackupSettingsScreen> createState() => _BackupSettingsScreenState();
}

class _BackupSettingsScreenState extends State<BackupSettingsScreen> {
  // 控制自动备份照片开关 - 从Provider获取
  bool get _autoBackupPhotos =>
      Provider.of<BackupProvider>(context, listen: false).autoBackupPhotos;

  // 控制自动备份视频开关 - 从Provider获取
  bool get _autoBackupVideos =>
      Provider.of<BackupProvider>(context, listen: false).autoBackupVideos;

  // 并行备份数量 - 从Provider获取
  int get _maxBackupCount =>
      Provider.of<BackupProvider>(context, listen: false).maxBackupCount;

  @override
  void initState() {
    super.initState();
    // 页面初始化后检查权限并加载相册
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkAndRequestPermission();
    });
  }

  /// 检查并请求相册权限
  Future<void> _checkAndRequestPermission() async {
    final albumProvider = Provider.of<AlbumProvider>(context, listen: false);
    final backupProvider = Provider.of<BackupProvider>(context, listen: false);

    // 检查当前权限状态
    final status = await Permission.photos.status;
    debugPrint('相册权限状态: $status');

    if (status.isGranted || status.isLimited) {
      // 已有权限，加载相册
      await albumProvider.loadAlbums(
        forceRefresh: false,
        autoBackupPhotos: backupProvider.autoBackupPhotos,
        autoBackupVideos: backupProvider.autoBackupVideos,
      );
    } else if (status.isDenied) {
      // 权限被拒绝，需要请求
      final result = await Permission.photos.request();
      debugPrint('请求权限结果: $result');

      if (result.isGranted || result.isLimited) {
        // 用户授予权限，加载相册
        await albumProvider.loadAlbums(
          forceRefresh: false,
          autoBackupPhotos: backupProvider.autoBackupPhotos,
          autoBackupVideos: backupProvider.autoBackupVideos,
        );
      } else {
        // 用户拒绝权限，显示提示
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('需要相册访问权限才能备份照片和视频'),
              duration: Duration(seconds: 3),
            ),
          );
        }
      }
    } else if (status.isPermanentlyDenied) {
      // 权限被永久拒绝，提示用户手动开启
      if (mounted) {
        _showPermissionDialog();
      }
    }
  }

  /// 显示权限设置对话框
  void _showPermissionDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => AlertDialog(
            title: const Text('需要相册访问权限'),
            content: const Text('咕噜备份需要访问相册权限才能备份照片和视频。请在设置中开启此权限。'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('稍后再说'),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  openAppSettings();
                },
                child: const Text('去设置'),
              ),
            ],
          ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 使用Consumer监听BackupProvider和AlbumProvider的变化
    return Consumer2<BackupProvider, AlbumProvider>(
      builder: (context, backupProvider, albumProvider, _) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('相册备份'),
            leading: IconButton(
              icon: const Icon(Icons.arrow_back),
              onPressed: () => Navigator.of(context).pop(),
            ),
            actions: [
              // 添加刷新按钮
              _buildRefreshButton(albumProvider, backupProvider),
            ],
          ),
          body: Column(
            children: [
              // 顶部提示区域，根据相册加载状态显示不同内容
              _buildTopNoticeArea(albumProvider),

              // 设置区域
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      // 自动备份照片
                      _buildSwitchOption(
                        title: '自动备份照片',
                        subtitle: '原图',
                        value: backupProvider.autoBackupPhotos,
                        onChanged: (value) async {
                          await backupProvider.setAutoBackupPhotos(value);

                          // 当两个开关都是关闭状态时，其中一个被打开，刷新设备名称
                          if (value && !backupProvider.autoBackupVideos ||
                              !value && !backupProvider.autoBackupVideos) {
                            await backupProvider.refreshDeviceName();
                          }

                          // 刷新相册排序
                          albumProvider.refreshAlbumSort(
                            backupProvider.autoBackupPhotos,
                            backupProvider.autoBackupVideos,
                          );
                        },
                      ),

                      // 自动备份视频
                      _buildSwitchOption(
                        title: '自动备份视频',
                        subtitle: '',
                        value: backupProvider.autoBackupVideos,
                        onChanged: (value) async {
                          await backupProvider.setAutoBackupVideos(value);

                          // 当两个开关都是关闭状态时，其中一个被打开，刷新设备名称
                          if (value && !backupProvider.autoBackupPhotos ||
                              !value && !backupProvider.autoBackupPhotos) {
                            await backupProvider.refreshDeviceName();
                          }

                          // 刷新相册排序
                          albumProvider.refreshAlbumSort(
                            backupProvider.autoBackupPhotos,
                            backupProvider.autoBackupVideos,
                          );
                        },
                      ),

                      // 原图备份选项
                      _buildSelectionOption(
                        title: '原图备份',
                        subtitle: '保留视频原始画质【推荐】',
                        badge: 'SVIP',
                        isSelected: true,
                      ),

                      // 压缩备份选项
                      _buildSelectionOption(
                        title: '压缩备份',
                        subtitle: '有损画质，视频压缩后上传',
                        isSelected: false,
                        onTap: () {
                          // 处理选项点击
                        },
                      ),

                      // 并行备份数量
                      _buildSettingsOption(
                        title: '并行备份数量',
                        subtitle: '最高${backupProvider.maxBackupCount}个',
                        trailing: const Icon(Icons.chevron_right),
                        onTap: () {
                          _showBackupCountDialog();
                        },
                      ),

                      // 使用手机流量备份照片
                      _buildSwitchOption(
                        title: '使用手机流量备份照片',
                        subtitle: '',
                        value: false,
                        onChanged: null,
                      ),

                      // 使用手机流量备份视频
                      _buildSwitchOption(
                        title: '使用手机流量备份视频',
                        subtitle: '',
                        value: false,
                        onChanged: null,
                      ),

                      // 相册备份信息
                      Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Row(
                          children: [
                            Expanded(
                              child: Row(
                                children: [
                                  Text(
                                    '照片及视频备份至: 设备: ${backupProvider.deviceName}',
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),

                      // 选择自动备份的相册
                      _buildAlbumSection(),

                      // 底部安全说明
                      Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.security,
                              size: 16,
                              color: Colors.grey.shade400,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              '咕噜噜保障你的数据安全',
                              style: TextStyle(
                                color: Colors.grey.shade400,
                                fontSize: 12,
                              ),
                            ),
                            TextButton(
                              onPressed: () {},
                              child: Text(
                                '查看详情 >',
                                style: TextStyle(
                                  color: Colors.grey.shade400,
                                  fontSize: 12,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建顶部提示区域
  Widget _buildTopNoticeArea(AlbumProvider albumProvider) {
    // 如果正在加载相册，显示加载进度
    if (albumProvider.status == AlbumLoadingStatus.loading) {
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
        color: Colors.blue.shade50,
        child: Row(
          children: [
            const SizedBox(
              width: 24,
              height: 24,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                '加载相册中: ${albumProvider.loadedCount}/${albumProvider.totalCount}',
              ),
            ),
          ],
        ),
      );
    } else if (albumProvider.status == AlbumLoadingStatus.error) {
      // 显示错误信息
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
        color: Colors.red.shade50,
        child: Row(
          children: [
            const Icon(Icons.error_outline, color: Colors.red),
            const SizedBox(width: 8),
            Expanded(child: Text('加载相册失败: ${albumProvider.errorMessage}')),
            TextButton(
              onPressed: () {
                _checkAndRequestPermission();
              },
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    // 否则显示加密备份提示
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
      color: Colors.blue.shade50,
      child: Row(
        children: [
          const Icon(Icons.shield, color: Colors.blue),
          const SizedBox(width: 8),
          const Expanded(child: Text('正在加密备份的相册内容至网盘')),
          TextButton(onPressed: () {}, child: const Text('查看进度 >')),
        ],
      ),
    );
  }

  // 开关选项
  Widget _buildSwitchOption({
    required String title,
    required String subtitle,
    required bool value,
    required ValueChanged<bool>? onChanged,
  }) {
    return ListTile(
      title: Text(title),
      subtitle: subtitle.isNotEmpty ? Text(subtitle) : null,
      trailing: Switch(
        value: value,
        onChanged: onChanged,
        activeColor: Colors.blue,
      ),
    );
  }

  // 选择选项
  Widget _buildSelectionOption({
    required String title,
    required String subtitle,
    String badge = '',
    required bool isSelected,
    VoidCallback? onTap,
  }) {
    return ListTile(
      title: Row(
        children: [
          Text(title),
          if (badge.isNotEmpty)
            Container(
              margin: const EdgeInsets.only(left: 8),
              padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
              decoration: BoxDecoration(
                color: Colors.amber.shade700,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                badge,
                style: const TextStyle(color: Colors.white, fontSize: 10),
              ),
            ),
        ],
      ),
      subtitle: Text(subtitle),
      trailing: isSelected ? const Icon(Icons.check, color: Colors.blue) : null,
      onTap: onTap,
    );
  }

  // 设置选项
  Widget _buildSettingsOption({
    required String title,
    required String subtitle,
    required Widget trailing,
    required VoidCallback onTap,
  }) {
    return ListTile(
      title: Text(title),
      subtitle: Text(subtitle),
      trailing: trailing,
      onTap: onTap,
    );
  }

  // 相册选择部分
  Widget _buildAlbumSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Padding(
          padding: EdgeInsets.only(left: 16.0, top: 16.0, bottom: 8.0),
          child: Text(
            '选择自动备份的相册',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        // 使用新的相册列表组件
        const SizedBox(
          height: 400, // 设置固定高度
          child: AlbumList(),
        ),
      ],
    );
  }

  // 显示备份数量选择对话框
  void _showBackupCountDialog() {
    final backupProvider = Provider.of<BackupProvider>(context, listen: false);

    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('选择并行备份数量'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                for (var i = 1; i <= 5; i++)
                  RadioListTile<int>(
                    title: Text('$i'),
                    value: i,
                    groupValue: backupProvider.maxBackupCount,
                    onChanged: (value) {
                      Navigator.of(context).pop();
                      if (value != null) {
                        backupProvider.setMaxBackupCount(value);
                      }
                    },
                  ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('取消'),
              ),
            ],
          ),
    );
  }

  // 给刷新按钮添加权限检查功能
  Widget _buildRefreshButton(
    AlbumProvider albumProvider,
    BackupProvider backupProvider,
  ) {
    return IconButton(
      icon: const Icon(Icons.refresh),
      onPressed:
          albumProvider.isLoading
              ? null
              : () async {
                // 先检查权限
                final status = await Permission.photos.status;
                if (status.isGranted || status.isLimited) {
                  // 有权限，直接刷新
                  albumProvider.forceRefreshAlbums(
                    autoBackupPhotos: backupProvider.autoBackupPhotos,
                    autoBackupVideos: backupProvider.autoBackupVideos,
                  );
                } else {
                  // 无权限，先请求
                  await _checkAndRequestPermission();
                }
              },
    );
  }
}
